package hyperNexusCommon

import (
	"bytes"
	"encoding/binary"
)

type MemoryStream struct {
	buffer *bytes.Buffer
	order  binary.ByteOrder
}

func NewMemoryStream(order binary.ByteOrder) *MemoryStream {
	return &MemoryStream{
		buffer: bytes.NewBuffer(make([]byte, 0, 1024*1024)),
		order:  order,
	}
}

func NewMemoryStreamWithBuff(order binary.ByteOrder, data []byte, isCopy bool) *MemoryStream {
	if isCopy {
		data = append([]byte{}, data...)
	}
	return &MemoryStream{
		buffer: bytes.NewBuffer(data),
		order:  order,
	}
}

func (this *MemoryStream) WriteData(data any) error {
	err := binary.Write(this.buffer, this.order, data)
	return err
}

func (this *MemoryStream) ReadData(data any) error {
	err := binary.Read(this.buffer, this.order, data)
	return err
}

func (this *MemoryStream) GetData() []byte {
	return this.buffer.Bytes()
}
